import datetime

from django import newforms as forms

class SplitDurationWidget(forms.MultiWidget):
    def __init__(self, attrs=None):
        attrs = attrs or {}
        widgets = (
            TextInput(attrs=dict(attrs, size=4, maxlength=10, title='Days')),
            TextInput(attrs=dict(attrs, size=1, maxlength=2, title='Hours')),
            TextInput(attrs=dict(attrs, size=1, maxlength=2, title='Minutes')),
            TextInput(attrs=dict(attrs, size=1, maxlength=2, title='Seconds')),
            TextInput(attrs=dict(attrs, size=5, maxlength=6, title='Microseconds')),
        )
        super(SplitDurationWidget, self).__init__(widgets, attrs)

    def decompress(self, value):
        if value:
            hours, seconds = divmod(value.seconds, 3600)
            minutes, seconds = divmod(seconds, 60)
            return [value.days, hours, minutes, seconds, value.microseconds]
        return [None, None, None, None, None]

    def format_output(self, rendered_widgets):
        return u'%s days, %s : %s : %s . %s' % tuple(rendered_widgets)

class SplitDurationField(forms.MultiValueField):
    widget = SplitDurationWidget

    def __init__(self, *args, **kwargs):
        fields = (
            IntegerField(label='Days', max_value=999999999, min_value=-999999999),
            IntegerField(label='Hours', max_value=23, min_value=0),
            IntegerField(label='Minutes', max_value=59, min_value=0),
            IntegerField(label='Seconds', max_value=59, min_value=0),
            IntegerField(label='Microseconds', max_value=999999, min_value=0),
        )
        super(SplitDurationField, self).__init__(fields, *args, **kwargs)

    def compress(self, data_list):
        if data_list == [None] * 5:
            raise ValidationError(gettext(u'This field is required.'))
        if data_list:
            return datetime.timedelta(
                days=data_list[0] or 0,
                hours=data_list[1] or 0,
                minutes=data_list[2] or 0,
                seconds=data_list[3] or 0,
                microseconds=data_list[4] or 0,
            )
        return None
